package cn.net.xinyi.xs.service.impl;

import java.io.Serializable;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import cn.net.xinyi.xs.Constants;
import cn.net.xinyi.xs.dao.Dao;
import cn.net.xinyi.xs.service.Manager;

/**
 * Base class for Business Services - use this class for utility methods and
 * generic CRUD methods.
 * 
 * @author <a href="mailto:caihualin2009@gmail.com">Cai Hua</a>
 */
public class BaseManager implements Manager {
	/**
	 * Log instance for all child classes. Uses LogFactory.getLog(getClass())
	 * from Commons Logging
	 */
	protected final Log log = LogFactory.getLog(getClass());

	/**
	 * UniversalDao instance, ready to charge forward and persist to the
	 * database
	 */
	protected Dao dao;

	public void setDao(Dao dao) {
		this.dao = dao;
	}

	/**
	 * {@inheritDoc}
	 */
	public Object get(Class clazz, Serializable id) {
		return dao.get(clazz, id);
	}

	/**
	 * {@inheritDoc}
	 */
	public List getAll(Class clazz) {
		return dao.getAll(clazz);
	}

	/**
	 * {@inheritDoc}
	 */
	public void remove(Class clazz, Serializable id) {
		dao.remove(clazz, id);
	}

	/**
	 * {@inheritDoc}
	 */
	public Object save(Object o) {
		return dao.save(o);
	}

	protected static Document generateDocument() {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder parser = null;
		try {
			parser = factory.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			try {
				parser = factory.newDocumentBuilder();
			} catch (ParserConfigurationException e1) {
				// ignore
			}
		}
		return parser.newDocument();
	}

	public static Document generateDocumentResult(long id, String result) {
		Document doc = generateDocument();
		Element root = doc.createElement(Constants.ROOT);
		doc.appendChild(root);
		Element resultNode = doc.createElement("result");
		Element messageNode = doc.createElement("messages");
		root.appendChild(resultNode);
		root.appendChild(messageNode);
		// ���ӷ���״̬
		resultNode.appendChild(doc.createTextNode(result));
		// ���ӷ�����Ϣ
		Element idNode = doc.createElement("id");
		idNode.appendChild(doc.createTextNode(String.valueOf(id)));
		messageNode.appendChild(idNode);
		return doc;
	}

	public static Document generateDocumentResult(String result) {
		Document doc = generateDocument();
		Element root = doc.createElement(Constants.ROOT);
		doc.appendChild(root);
		Element resultNode = doc.createElement("result");
		root.appendChild(resultNode);
		// ���ӷ���״̬
		resultNode.appendChild(doc.createTextNode(result));
		return doc;
	}
}
